// require('dotenv').config()
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const ReactRefreshTypeScript = require('react-refresh-typescript');

module.exports = {
  mode: 'development',
  entry: {
    index: './src/index.ts'
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
  devtool: 'cheap-module-source-map',
  devServer: {
    static: path.join(__dirname, 'dist'),
    port: '8441',
    compress: true,
    historyApiFallback: true,
    hot: true
  },
  watchOptions: {
    ignored: /node_modules/,
  },
  module: {
    rules: [
      {
        test: /\.ts|\.tsx$/,
        exclude: /node_modules/,
        use: [
          'babel-loader',
          {
            loader: 'ts-loader',
            options: {
              transpileOnly: true,  // 只编译不校验类型，类型检查由 fork-ts-checker-webpack-plugin 独立线程处理
              getCustomTransformers: () => ({
                before: [
                  ReactRefreshTypeScript()
                ]
              }),
            }
          },
        ],
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|webp|tiff|bmp)$/,
        type: 'asset',
      },
      {
        test: /\.s[ac]ss$/,
        exclude: /node_modules/,
        use: [
          'style-loader', 
          'css-loader', 
          'sass-loader', 
          'postcss-loader',
          {
            loader: 'sass-resources-loader',
            options: {
              resources: './src/assets/styles/variables.scss'
            }
          },
        ]
      }
    ],
  },
  plugins: [
    new NodePolyfillPlugin(),
    new HtmlWebpackPlugin({
      title: 'Mcool',
      template: './public/index.html',
      filename: 'index.html',
      favicon: './public/favicon.ico'
    }),
    new ForkTsCheckerWebpackPlugin(),
    new ReactRefreshWebpackPlugin(),
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
    extensions: ['.tsx', '.ts', '.js', '.scss', '.json']
  },
};